package v1

import (
	"sweetsunnyflower/app/models/suggest"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/auth"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type SuggestsController struct {
	Controller
}

func (ctrl *SuggestsController) Index(c *gin.Context) {
	suggests := suggest.All()
	response.Data(c, suggests)
}

func (ctrl *SuggestsController) Show(c *gin.Context) {
	suggestModel := suggest.Get(c.Param("id"))
	if suggestModel.ID == 0 {
		response.Abort404(c)
		return
	}
	response.Data(c, suggestModel)
}

func (ctrl *SuggestsController) Store(c *gin.Context) {

	request := requests.SuggestRequest{}
	if ok := requests.Validate(c, &request, requests.SuggestSave); !ok {
		return
	}

	suggestModel := suggest.Suggest{
		UserID:  auth.CurrentIntUID(c),
		Type:    request.Type,
		Suggest: request.Suggest,
		Contact: request.Contact,
	}
	suggestModel.Create()
	if suggestModel.ID > 0 {
		response.Created(c, suggestModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *SuggestsController) Update(c *gin.Context) {

	suggestModel := suggest.Get(c.Param("id"))
	if suggestModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifySuggest(c, suggestModel); !ok {
		response.Abort403(c)
		return
	}

	request := requests.SuggestRequest{}
	if ok := requests.Validate(c, &request, requests.SuggestSave); !ok {
		return
	}

	// suggestModel.FieldName = request.FieldName
	rowsAffected := suggestModel.Save()
	if rowsAffected > 0 {
		response.Data(c, suggestModel)
	} else {
		response.Abort500(c, "更新失败，请稍后尝试~")
	}
}

func (ctrl *SuggestsController) Delete(c *gin.Context) {

	suggestModel := suggest.Get(c.Param("id"))
	if suggestModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifySuggest(c, suggestModel); !ok {
		response.Abort403(c)
		return
	}

	rowsAffected := suggestModel.Delete()
	if rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
